﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;

namespace DepartmentSpecificStoreView
{
    [Guid( "68744297-a604-483a-931c-a8d9a66297ae" )]
    public class DepartmentSpecificGridView : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private bool _error = false;


        public DepartmentSpecificGridView( )
        {
            this.ExportMode = WebPartExportMode.All;
        }

        /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls( )
        {
            if ( !_error )
            {
                try
                {

                    base.CreateChildControls( );
                    //DepartmentSpecificUserControl
                    DepartmentSpecificStoreViewControl myControl = ( DepartmentSpecificStoreViewControl ) Page.LoadControl( "~/_controltemplates/DepartmentSpecificUserControl/DepartmentSpecificStoreViewControl.ascx" );
                    this.Controls.Add( myControl );


                }
                catch ( Exception ex )
                {
                    HandleException( ex );
                }
            }
        }

        /// <summary>
        /// Ensures that the CreateChildControls() is called before events.
        /// Use CreateChildControls() to create your controls.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad( EventArgs e )
        {
            if ( !_error )
            {
                try
                {
                    base.OnLoad( e );
                    this.EnsureChildControls( );

                    // Your code here...
                }
                catch ( Exception ex )
                {
                    HandleException( ex );
                }
            }
        }

        /// <summary>
        /// Clear all child controls and add an error message for display.
        /// </summary>
        /// <param name="ex"></param>
        private void HandleException( Exception ex )
        {
            this._error = true;
            this.Controls.Clear( );
            this.Controls.Add( new LiteralControl( ex.Message ) );
        }
    }
}
